package middleware

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// Cors 跨域访问中间件
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE, UPDATE")
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Token")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header("Access-Control-Allow-Credentials", "true")
		}

		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

// Logger 日志中间件
func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		logrus.Info(c.Request.Host)     // localhost:8080
		logrus.Info(c.Request.Proto)    // HTTP/1.1
		logrus.Info(c.Request.URL.Path) // HTTP/1.1
		logrus.Info(c.Writer.Status())  // HTTP/1.1
		// 如果检测到请求头不符合规范，则终止请求处理
		// if c.GetHeader("Content-Type") != "application/json" {
		//	c.AbortWithStatusJSON(http.StatusBadRequest, api.H{"error": "Invalid Content-Type"})
		//	return
		// }

		start := time.Now()
		c.Next()
		end := time.Now()
		logrus.WithFields(logrus.Fields{
			"method": c.Request.Method,
			"path":   c.Request.URL.Path,
			"status": c.Writer.Status(),
			"times":  end.Sub(start),
		}).Info("处理请求")
	}
}
